<template>
  <div class="meal-plan-container">
    <!-- 顶部操作栏 -->
    <el-card class="action-card" shadow="hover">
      <div class="action-header">
        <div class="left">
          <el-button type="primary" @click="createPlan">
            创建计划
          </el-button>
          <el-button @click="showTemplates">
            从模板创建
          </el-button>
        </div>
        <div class="right">
          <el-radio-group v-model="viewMode" size="small">
            <el-radio-button :value="'list'">列表视图</el-radio-button>
            <el-radio-button :value="'calendar'">日历视图</el-radio-button>
          </el-radio-group>
        </div>
      </div>
    </el-card>

    <!-- 推荐计划卡片 -->
    <el-card v-if="recommendedPlan" class="recommended-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>推荐计划</span>
          <el-button type="primary" link @click="useRecommendedPlan">
            使用此计划
          </el-button>
        </div>
      </template>
      <div class="plan-overview">
        <div class="plan-info">
          <h3>根据您的目标生成的推荐计划</h3>
          <p>每日热量: {{ recommendedPlan.dailyCalories }}kcal</p>
          <div class="nutrition-distribution">
            <el-tag>蛋白质: {{ recommendedPlan.protein }}g</el-tag>
            <el-tag type="success">碳水: {{ recommendedPlan.carbs }}g</el-tag>
            <el-tag type="warning">脂肪: {{ recommendedPlan.fat }}g</el-tag>
          </div>
        </div>
        <el-button type="primary" @click="useRecommendedPlan">
          应用计划
        </el-button>
      </div>
    </el-card>

    <!-- 列表视图 -->
    <template v-if="viewMode === 'list'">
      <el-card v-for="plan in mealPlans" :key="plan.id" class="plan-card" shadow="hover">
        <div class="plan-header">
          <div class="plan-title">
            <h3>{{ plan.name }}</h3>
            <el-tag :type="plan.status === 'active' ? 'success' : 'info'">
              {{ plan.status === 'active' ? '进行中' : '已完成' }}
            </el-tag>
          </div>
          <div class="plan-actions">
            <el-button type="primary" link @click="editPlan(plan)">
              编辑
            </el-button>
            <el-button type="danger" link @click="deletePlan(plan)">
              删除
            </el-button>
          </div>
        </div>
        
        <div class="plan-content">
          <div class="plan-meals">
            <div v-for="(meals, day) in plan.meals" :key="day" class="day-meals">
              <h4>{{ formatDate(day) }}</h4>
              <div class="meal-list">
                <div v-for="meal in meals" :key="meal.id" class="meal-item">
                  <span class="meal-type">{{ getMealTypeText(meal.type) }}</span>
                  <span class="meal-food">{{ meal.food.name }}</span>
                  <span class="meal-amount">{{ meal.amount }}g</span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="plan-summary">
            <h4>营养摄入</h4>
            <div class="nutrition-info">
              <el-progress
                type="dashboard"
                :percentage="(plan.currentCalories / plan.targetCalories) * 100"
                :color="getProgressColor"
              >
                <template #default>
                  <div class="progress-value">
                    <span>{{ plan.currentCalories }}</span>
                    <span class="progress-label">/ {{ plan.targetCalories }}kcal</span>
                  </div>
                </template>
              </el-progress>
              <div class="nutrition-details">
                <div class="nutrition-item">
                  <span class="label">蛋白质</span>
                  <el-progress
                    :percentage="(plan.currentProtein / plan.targetProtein) * 100"
                    :color="getProgressColor"
                  />
                </div>
                <div class="nutrition-item">
                  <span class="label">碳水</span>
                  <el-progress
                    :percentage="(plan.currentCarbs / plan.targetCarbs) * 100"
                    :color="getProgressColor"
                  />
                </div>
                <div class="nutrition-item">
                  <span class="label">脂肪</span>
                  <el-progress
                    :percentage="(plan.currentFat / plan.targetFat) * 100"
                    :color="getProgressColor"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </template>

    <!-- 日历视图 -->
    <el-card v-else class="calendar-card" shadow="hover">
      <el-calendar v-model="currentDate">
        <template #dateCell="{ data }">
          <div class="calendar-cell">
            <span>{{ data.day.split('-').slice(2).join('') }}</span>
            <div v-if="getDayMeals(data.day)" class="day-meals">
              <div
                v-for="meal in getDayMeals(data.day)"
                :key="meal.id"
                class="calendar-meal-item"
              >
                {{ getMealTypeText(meal.type) }}: {{ meal.food.name }}
              </div>
            </div>
          </div>
        </template>
      </el-calendar>
    </el-card>

    <!-- 创建/编辑计划对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentPlan ? '编辑计划' : '创建计划'"
      width="60%"
    >
      <el-form ref="formRef" :model="planForm" :rules="rules" label-width="100px">
        <el-form-item label="计划名称" prop="name">
          <el-input v-model="planForm.name" placeholder="输入计划名称" />
        </el-form-item>
        
        <el-form-item label="计划日期" prop="dateRange">
          <el-date-picker
            v-model="planForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled-date="disabledDate"
          />
        </el-form-item>

        <el-form-item label="每日目标">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="热量" prop="targetCalories">
                <el-input-number
                  v-model="planForm.targetCalories"
                  :min="0"
                  :step="100"
                >
                  <template #append>kcal</template>
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="蛋白质" prop="targetProtein">
                <el-input-number
                  v-model="planForm.targetProtein"
                  :min="0"
                  :step="5"
                >
                  <template #append>g</template>
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="碳水" prop="targetCarbs">
                <el-input-number
                  v-model="planForm.targetCarbs"
                  :min="0"
                  :step="5"
                >
                  <template #append>g</template>
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="脂肪" prop="targetFat">
                <el-input-number
                  v-model="planForm.targetFat"
                  :min="0"
                  :step="5"
                >
                  <template #append>g</template>
                </el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="膳食安排">
          <div v-for="(day, index) in planForm.meals" :key="index" class="day-plan">
            <h4>{{ formatDate(day.date) }}</h4>
            <div v-for="meal in day.meals" :key="meal.id" class="meal-plan">
              <el-select v-model="meal.type" placeholder="选择餐次">
                <el-option label="早餐" value="breakfast" />
                <el-option label="午餐" value="lunch" />
                <el-option label="晚餐" value="dinner" />
                <el-option label="加餐" value="snack" />
              </el-select>
              <el-select
                v-model="meal.foodId"
                filterable
                remote
                reserve-keyword
                placeholder="搜索食物"
                :remote-method="handleFoodSearch"
                :loading="foodSearchLoading"
              >
                <el-option
                  v-for="item in foodOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <span>{{ item.name }}</span>
                  <span class="food-option-info">
                    {{ item.calories }}kcal/100g
                  </span>
                </el-option>
              </el-select>
              <el-input-number
                v-model="meal.amount"
                :min="1"
                :max="1000"
                :step="10"
              >
                <template #append>g</template>
              </el-input-number>
              <el-button
                type="danger"
                icon="Delete"
                circle
                @click="removeMeal(day, meal)"
              />
            </div>
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="addMeal(day)"
            >
              添加餐次
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="计划类型" prop="planType">
          <el-radio-group v-model="planForm.planType">
            <el-radio-button :value="'once'">单次</el-radio-button>
            <el-radio-button :value="'daily'">每日</el-radio-button>
            <el-radio-button :value="'weekly'">每周</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 模板选择对话框 -->
    <el-dialog
      v-model="templateDialogVisible"
      title="选择模板"
      width="50%"
    >
      <div class="template-list">
        <el-card
          v-for="template in templates"
          :key="template.id"
          class="template-card"
          shadow="hover"
          @click="useTemplate(template)"
        >
          <div class="template-info">
            <h3>{{ template.name }}</h3>
            <p>{{ template.description }}</p>
            <div class="template-stats">
              <el-tag>{{ template.days }}天</el-tag>
              <el-tag type="success">{{ template.calories }}kcal/天</el-tag>
            </div>
          </div>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils/date'
import { debounce } from '@/utils'
import { searchFood } from '@/api/food'
import { useRouter } from 'vue-router'

const store = useStore()
const router = useRouter()
const formRef = ref(null)
const currentDate = ref(new Date())
const viewMode = ref('list')
const dialogVisible = ref(false)
const templateDialogVisible = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const foodSearchLoading = ref(false)
const foodOptions = ref([])

// 从 store 获取数据
const mealPlans = computed(() => store.state.mealPlan.mealPlans)
const recommendedPlan = computed(() => store.state.mealPlan.recommendedPlan)
const templates = computed(() => store.state.mealPlan.templates)
const total = computed(() => store.state.mealPlan.total)
const currentPlan = computed(() => store.state.mealPlan.currentPlan)

// 计划表单
const planForm = ref({
  name: '',
  dateRange: [],
  targetCalories: 2000,
  targetProtein: 100,
  targetCarbs: 250,
  targetFat: 70,
  meals: [],
  planType: 'daily'
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入计划名称', trigger: 'blur' }
  ],
  dateRange: [
    { required: true, message: '请选择计划日期', trigger: 'change' }
  ],
  targetCalories: [
    { required: true, message: '请设置目标热量', trigger: 'blur' }
  ]
}

// 获取餐次文本
const getMealTypeText = (type) => {
  const types = {
    breakfast: '早餐',
    lunch: '午餐',
    dinner: '晚餐',
    snack: '加餐'
  }
  return types[type] || type
}

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage < 80) return '#409EFF'
  if (percentage < 100) return '#67C23A'
  return '#F56C6C'
}

// 日期限制
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 不能选择过去的日期
}

// 创建计划
const createPlan = () => {
  planForm.value = {
    name: '',
    dateRange: [],
    targetCalories: 2000,
    targetProtein: 100,
    targetCarbs: 250,
    targetFat: 70,
    meals: [],
    planType: 'daily'
  }
  dialogVisible.value = true
}

// 编辑计划
const editPlan = async (plan) => {
  try {
    await store.dispatch('mealPlan/getMealPlanDetail', plan.id)
    const currentPlan = store.state.mealPlan.currentPlan
    planForm.value = {
      ...currentPlan,
      dateRange: [new Date(currentPlan.startDate), new Date(currentPlan.endDate)],
      planType: currentPlan.planType
    }
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取计划详情失败')
  }
}

// 删除计划
const deletePlan = async (plan) => {
  try {
    await ElMessageBox.confirm('确定要删除此计划吗？', '提示', {
      type: 'warning'
    })
    await store.dispatch('mealPlan/deleteMealPlan', plan.id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 显示模板列表
const showTemplates = async () => {
  try {
    await store.dispatch('mealPlan/getPlanTemplates')
    templateDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取模板失败')
  }
}

// 使用模板
const useTemplate = async (template) => {
  try {
    await store.dispatch('mealPlan/createFromTemplate', template.id)
    templateDialogVisible.value = false
    ElMessage.success('创建成功')
  } catch (error) {
    ElMessage.error('创建失败')
  }
}

// 使用推荐计划
const useRecommendedPlan = () => {
  if (!recommendedPlan.value) return
  planForm.value = {
    name: '推荐计划',
    dateRange: [new Date(), new Date(Date.now() + 6 * 8.64e7)], // 7天计划
    targetCalories: recommendedPlan.value.dailyCalories,
    targetProtein: recommendedPlan.value.protein,
    targetCarbs: recommendedPlan.value.carbs,
    targetFat: recommendedPlan.value.fat,
    meals: [],
    planType: 'daily'
  }
  dialogVisible.value = true
}

// 添加餐次
const addMeal = (day) => {
  day.meals.push({
    id: Date.now(),
    type: '',
    foodId: null,
    amount: 100
  })
}

// 移除餐次
const removeMeal = (day, meal) => {
  const index = day.meals.indexOf(meal)
  if (index !== -1) {
    day.meals.splice(index, 1)
  }
}

// 搜索食物
const handleFoodSearch = debounce(async (query) => {
  if (!query) return
  try {
    foodSearchLoading.value = true
    const res = await searchFood({ keyword: query })
    foodOptions.value = res.data.list
  } catch (error) {
    console.error('搜索食物失败:', error)
  } finally {
    foodSearchLoading.value = false
  }
}, 300)

// 获取日期的膳食
const getDayMeals = (day) => {
  const plan = mealPlans.value.find(p => {
    return day >= p.startDate && day <= p.endDate
  })
  return plan?.meals[day] || null
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      const data = {
        ...planForm.value,
        startDate: planForm.value.dateRange[0],
        endDate: planForm.value.dateRange[1]
      }

      if (!validatePlanData(data)) return

      try {
        if (currentPlan.value) {
          await store.dispatch('mealPlan/updateMealPlan', {
            id: currentPlan.value.id,
            data
          })
        } else {
          await store.dispatch('mealPlan/createMealPlan', data)
        }
        ElMessage.success(currentPlan.value ? '更新成功' : '创建成功')
        dialogVisible.value = false
        fetchData() // 刷新列表数据
      } catch (error) {
        ElMessage.error(currentPlan.value ? '更新失败' : '创建失败')
      }
    }
  })
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 获取数据
const fetchData = async () => {
  try {
    await store.dispatch('mealPlan/getMealPlans', {
      page: currentPage.value,
      pageSize: pageSize.value
    })
  } catch (error) {
    ElMessage.error('获取数据失败')
  }
}

// 监听日期范围变化
watch(() => planForm.value.dateRange, (newRange) => {
  if (!newRange || !newRange[0] || !newRange[1]) return
  
  // 生成日期范围内的每一天
  const days = []
  const start = new Date(newRange[0])
  const end = new Date(newRange[1])
  
  while (start <= end) {
    days.push({
      date: formatDate(start),
      meals: []
    })
    start.setDate(start.getDate() + 1)
  }
  
  planForm.value.meals = days
}, { deep: true })

// 初始化数据
onMounted(async () => {
  try {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }

    loading.value = true
    await Promise.all([
      store.dispatch('mealPlan/getMealPlans', {
        page: currentPage.value,
        pageSize: pageSize.value
      }),
      store.dispatch('mealPlan/getRecommendedPlan').catch(() => {
        // 忽略推荐计划获取失败的错误
        console.warn('获取推荐计划失败')
      })
    ])
  } catch (error) {
    console.error('初始化失败:', error)
    if (error.message === '用户ID不存在') {
      ElMessage.error('请先登录')
      router.push('/login')
    } else {
      ElMessage.error('获取数据失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
})

// 验证膳食计划数据
const validatePlanData = (data) => {
  // 验证每天是否都有膳食安排
  const hasEmptyDay = data.meals.some(day => !day.meals.length)
  if (hasEmptyDay) {
    ElMessage.warning('请确保每天都有膳食安排')
    return false
  }

  // 验证每个膳食是否都选择了食物
  const hasInvalidMeal = data.meals.some(day => 
    day.meals.some(meal => !meal.type || !meal.foodId || !meal.amount)
  )
  if (hasInvalidMeal) {
    ElMessage.warning('请完善所有膳食的信息')
    return false
  }

  return true
}

// 计算计划的营养摄入进度
// 计算计划的完成度
// 格式化营养数值
// 添加日历相关方法

// 获取日期样式
// 格式化日期单元格内容
// 添加视图模式切换监听
watch(viewMode, (newMode) => {
  if (newMode === 'calendar') {
    nextTick(() => {
      // 在切换到日历视图时重新初始化图表
      if (weightChart.value) {
        weightChart.value.resize()
      }
      if (nutritionChart.value) {
        nutritionChart.value.resize()
      }
    })
  }
})

// 添加图表相关变量
const weightChart = ref(null)
const nutritionChart = ref(null)

// 添加 loading 变量
const loading = ref(false)
</script>

<style lang="scss" scoped>
.meal-plan-container {
  padding: 20px;

  .action-card {
    margin-bottom: 20px;

    .action-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .left {
        display: flex;
        gap: 12px;
      }
    }
  }

  .recommended-card {
    margin-bottom: 20px;

    .plan-overview {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .plan-info {
        h3 {
          margin: 0 0 12px;
        }

        p {
          margin: 0 0 16px;
          color: var(--el-text-color-secondary);
        }

        .nutrition-distribution {
          display: flex;
          gap: 12px;
        }
      }
    }
  }

  .plan-card {
    margin-bottom: 20px;

    .plan-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .plan-title {
        display: flex;
        align-items: center;
        gap: 12px;

        h3 {
          margin: 0;
        }
      }
    }

    .plan-content {
      display: grid;
      grid-template-columns: 2fr 1fr;
      gap: 24px;

      .plan-meals {
        .day-meals {
          margin-bottom: 20px;

          h4 {
            margin: 0 0 12px;
            padding-bottom: 8px;
            border-bottom: 1px solid var(--el-border-color-lighter);
          }

          .meal-list {
            .meal-item {
              display: flex;
              align-items: center;
              padding: 8px 0;

              .meal-type {
                width: 80px;
                color: var(--el-text-color-secondary);
              }

              .meal-food {
                flex: 1;
              }

              .meal-amount {
                color: var(--el-text-color-secondary);
              }
            }
          }
        }
      }

      .plan-summary {
        h4 {
          margin: 0 0 16px;
        }

        .nutrition-info {
          .progress-value {
            font-size: 16px;
            font-weight: bold;

            .progress-label {
              font-size: 12px;
              font-weight: normal;
              color: var(--el-text-color-secondary);
            }
          }

          .nutrition-details {
            margin-top: 24px;

            .nutrition-item {
              margin-bottom: 16px;

              .label {
                display: inline-block;
                width: 60px;
                margin-right: 8px;
              }
            }
          }
        }
      }
    }
  }

  .calendar-card {
    .calendar-cell {
      height: 100%;
      display: flex;
      flex-direction: column;
      
      .day-meals {
        margin-top: 8px;
        font-size: 12px;

        .calendar-meal-item {
          padding: 2px 4px;
          margin-bottom: 2px;
          background-color: var(--el-color-primary-light-9);
          border-radius: 2px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
}

.template-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;

  .template-card {
    cursor: pointer;

    .template-info {
      h3 {
        margin: 0 0 8px;
      }

      p {
        margin: 0 0 16px;
        color: var(--el-text-color-secondary);
      }

      .template-stats {
        display: flex;
        gap: 8px;
      }
    }
  }
}

.food-option-info {
  float: right;
  color: var(--el-text-color-secondary);
  font-size: 13px;
}
</style> 